#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 17:26
# @Author  : Tom_zc
# @FileName: publish-tag.py
# @Software: PyCharm
import sys
import logging
import click
from pathlib import Path

CURR_DIR = Path(__file__).resolve()
ROOT_DIR = CURR_DIR.parent.parent.parent.parent
sys.path.append(ROOT_DIR.as_posix())

from scripts.utils.gitcode_helper import GitCodeHelper
from scripts.utils.parse_params import parse_repo_info_by_webhook_payload
from scripts.utils.common import func_retry

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

_COMMENT_TAG_EXIST_FAILED = "Tag({}) exist in repo, please update version and create new pr."


class PublishTagHelper:

    def __init__(self, owner, repo, token, pr_number):
        self.git_helper = GitCodeHelper(owner, repo, pr_number, token)

    @func_retry()
    def create_tag(self, branch, tag):
        info = self.git_helper.get_tag()
        names = [item['name'] for item in info]
        exists = tag in names
        if exists:
            logging.error("tag {} already, Please delete {}".format(names, tag))
            # todo gitcode暂时不提供删除tag的接口，已经向gitcode提需求，目前只能通过评论的方式提醒。
            # self.git_helper.delete_tag(tag)
            self.git_helper.create_comment({"body": _COMMENT_TAG_EXIST_FAILED.format(tag)})
            sys.exit(1)
        else:
            self.git_helper.create_tag({"refs": branch, "tag_name": tag})


@click.command()
@click.option("--gitcode_token", help='gitcode_token')
@click.option("--tag", help='tag')
def main(gitcode_token, tag):
    owner, repo, branch, pr_number, _ = parse_repo_info_by_webhook_payload()
    publish_tag_helper = PublishTagHelper(owner, repo, gitcode_token, pr_number)
    logging.info("create tag {} for branch {}....".format(tag, branch))
    publish_tag_helper.create_tag(branch, tag)


if __name__ == '__main__':
    main()
